import router from './index';
import store from '@/store/index';
import { menuList } from '../../JSONdata/menu.json';

const addAsyncRouter = async () => {
  // 1.获取路由数据
  const DATA = menuList;

  // 2.存入vux中
  store.commit('user/setMenuList', DATA);

  // 路由外层包裹
  let layOut = {
    path: '/home',
    name: 'home',
    meta: { title: '首页' },
    redirect: '/home/meteorology',
    component: () => import('../views/HomeView/HomeView.vue'),
    children: [],
  };
  Manufacturingrouting(DATA); //处理成路由数据

  layOut.children = oneleave;
  router.addRoute(layOut);
};

let oneleave = [];

function Manufacturingrouting(data) {
  data.forEach((item, index) => {
    // 路由扁平化
    if (!item.children || item.children === []) {
      oneleave.push({
        path: item.path,
        name: item.name,
        meta: { title: item.title },
        component: () => import(`../views${item.page}`),
      });
    }
    if (item.children && item.children.length > 0) {
      Manufacturingrouting(item.children);
    }
  });
}

const arrayTreeAddLevel = (array, childrenName = 'children') => {
  if (!Array.isArray(array)) return [];

  const recursive = (array) => {
    return array.map((v) => {
      v['path'] = v.path;
      v['name'] = v.name;
      v['meta'] = { title: v.title };
      v['component'] = () => import(`../views${v.page}`);

      const child = v[childrenName];
      if (child && child.length) recursive(child);
      return v;
    });
  };

  return recursive(array);
};

export default addAsyncRouter;
